<?php
namespace Api\Controller;
use \Common\Library\Job\Group;
use \Common\Library\Job\Order;
class IndexController extends APIController{
    /*待验证的参数*/
    public $tca = [
        'order_id' => [
            'method' => 'exists',
            'model' => 'order',
            'code_key' => 'lawless'
        ],
    ];
    //调试接口页面
    public function index(){
        try{
            //$this->safeChecked();
            static $data = [];
            $data['banner'] = [];
            //首页banner
            $banner = M('Banner')->Field('crdate,image')->select();
            if($banner){
                foreach ($banner as $key => $value) {
                    $data['banner'][] = C('DOMAIN_URL').C('PATH_UPLOAD').'Banner/'.date('Ym',$value['crdate']).'/'.$value['image'];
                }
            }
            $data['image'] = '';
            if($this->Config['adv']){
                $data['image'] = C('DOMAIN_URL').C('PATH_UPLOAD').$this->Config['adv'];
            }
            $SeckillTime = M('seckill_time');
            /*//所有时间段
            $data['times'] = M('seckill_time')->select();
            //当前时间段的神秘团
            $now_time = date('H:i');
            $kill_time = $SeckillTime->where(array('time' => array('lt',$now_time)))->limit(0,1)->order('time desc')->select();
            $Activity = M('activity');
            $data['secret_group'] = '';
            if($kill_time){
                $secret_group = $Activity
                                ->alias('a')
                                ->join(C('DB_PREFIX').'seckill as b on a.id = b.activity_id')
                                ->join(C('DB_PREFIX').'goods as c on c.id = a.goods_id')
                                ->where(array('a.deleted' => 0,'a.hidden' => 0,'a.start' => array('lt',time()),'a.end' => array('gt', time()),'b.deleted' => 0,'b.time_id' => $kill_time[0]['id'],'c.deleted' => 0,'c.hidden' => 0))
                                ->Field('a.id as aid,c.id,c.name,c.image,c.crdate,c.remark')
                                ->select();
                if($secret_group){
                    //获取最低拼团价
                    $activity_price = M('plan')->where(array('activity_id' => $secret_group[0]['id'],'deleted' => 0))->Field('group_price,leader_price')->order('group_price asc')->select();
                    $data['secret_group'] = [
                        'image' => C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$secret_group[0]['crdate']).'/'.$secret_group[0]['image'],
                        'name' => $secret_group[0]['name'],
                        'remark' => explode(',', $secret_group[0]['remark']),
                        'id' => $secret_group[0]['id'],
                        'activity_id' => $secret_group[0]['aid']
                    ];
                }
            }*/
            //获取所有限时团
            $Activity = M('activity');
            $secret_group = $Activity
                            ->alias('a')
                            ->join(C('DB_PREFIX').'seckill as b on a.id = b.activity_id')
                            ->join(C('DB_PREFIX').'goods as c on c.id = a.goods_id')
                            ->join(C('DB_PREFIX').'seckill_time as d on d.id = b.time_id')
                            ->where(array('a.deleted' => 0,'a.hidden' => 0,'a.start' => array('lt',time()),'a.end' => array('gt', time()),'b.deleted' => 0,'c.deleted' => 0,'c.hidden' => 0))
                            ->Field('a.id as aid,c.id,c.name,c.image,c.crdate,c.remark,d.time')
                            ->order('d.time asc,b.crdate desc')
                            ->group('d.id')
                            ->select();
            $data['secret_group'] = [];
            $data['secret_index'] = 0;
            if($secret_group){
                $Plan = M('plan');
                foreach ($secret_group as $key => &$value) {
                    if(date('H:i') >= $value['time']){
                        $data['secret_index'] = $key;
                    }
                    //获取最低拼团价
                    $activity_price = $Plan->where(array('activity_id' => $value['aid'],'deleted' => 0))->Field('leader_price')->order('leader_price asc')->select();
                    $data['secret_group'][$key] = [
                        'image' => C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$value['crdate']).'/'.$value['image'],
                        'name' => $value['name'],
                        'remark' => explode(',', $value['remark']),
                        'id' => $value['id'],
                        'activity_id' => $value['aid'],
                        'price' => $activity_price[0]['leader_price'],
                        'time' => $value['time']
                    ];
                }
            }

            $data['normal_group'] = [];
            //普通团-默认按创建时间倒序
            $normal_activity = $Activity
                                ->alias('a')
                                ->join(C('DB_PREFIX').'goods as b on b.id = a.goods_id')
                                ->where(array('a.deleted' => 0,'a.type' => 1,'a.hidden' => 0,'a.start' => array('lt',time()),'a.end' => array('gt', time()),'b.deleted' => 0,'b.hidden' => 0))
                                ->Field('a.id as aid,a.num,b.id,b.name,b.image,b.crdate,b.remark')
                                ->limit(0,5)
                                ->order('a.crdate desc')
                                ->select();
            $Group = M('group');
            $Order = M('order');
            if($normal_activity){
                foreach ($normal_activity as $key => $value) {
                    //获取最低拼团价
                    $activity_price = M('plan')->where(array('activity_id' => $value['aid'],'deleted' => 0))->Field('group_price')->order('group_price asc')->limit(0,1)->select();
                    $data['normal_group'][$key]['image'] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$value['crdate']).'/'.$value['image'];
                    $data['normal_group'][$key]['name'] = $value['name'];
                    $data['normal_group'][$key]['remark'] = explode(',', $value['remark']);
                    $data['normal_group'][$key]['goods_id'] = $value['id'];
                    $data['normal_group'][$key]['id'] = $value['aid'];
                    $data['normal_group'][$key]['num'] = $value['num'];
                    $data['normal_group'][$key]['price'] = $activity_price[0]['group_price'];
                    //获取该活动下的所有开团数量
                    $groups = $Group->where(array('activity_id' => $value['aid']))->Field('id')->select();
                    $group_ids = [];
                    if($groups){
                        $group_ids = array_map(function($val){
                            return $group_ids[] = $val['id'];
                        },$groups);
                    }
                    $data['normal_group'][$key]['sales'] = 0;
                    if($group_ids){
                        $data['normal_group'][$key]['sales'] = $Order->where(array('group_id' => array('IN',$group_ids)))->count()?:0;
                    }
                }
            }
            $this->res_data['data'] = $data?:array();
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
        
            
        //通知
        /*vendor('Aliyun.DySDKLite.Sms.sendSms');
        $key = 'LTAIIJwUUxRhkZD7';
        $secret = 'Uz9aAl6BeSPn1Ne3lflNJUD3W8mhX4';
        //派单提醒
        $param = [
            'PhoneNumbers' => 18368022817,
            'SignName' => '拼好菜',
            'TemplateCode' => 'SMS_155830022',
            'TemplateParam' => [
                'code' => '123456'
            ]
        ];
        $send = new \Aliyun\DySDKLite\Sms\sendSms($key,$secret,$param);
        $result = $send->send();
        p(json_encode($result,true));
        if($result->Code != 'OK'){
            debug(json_encode($result,true));
            $this->error('分配失败：发送派单消息不成功');
        }*/
    	/*$class = new Group(1);
    	p($class->handle());
    	p(\Common\Library\Job\Group::$time);*/
    	/*$param = [
            'com' => 'suning',
            'num' => '0052202739270101'
        ];
        P(selectPostage($param));*/
    }

    //拼团及订单延迟处理
    public function doRequest(){
        debug(file_get_contents("php://input"));
        $data = file_get_contents("php://input");
        set_time_limit (0);
        sleep(900);
        debug(date("Y-m-d H:i:s"));
        $class = new Order($data['id']);
        $class->handle();
        /*$class = new Group(1);
        $class->handle();*/
        //p($class->handle());
        //p(\Common\Library\Job\Group::$time);
    }

    //发送请求
    public function dealy(){
        $class = new Order($data['id']);
        $class->handle();
        /*$url = 'http://teambuy.zero.com/api/index/doRequest';
        $data = ['a' => 2,'b' => 3,'c' => 4];
        syncRequest($url,$data,'post');*/
        /*$info = parse_url($url);
        $fp = fsockopen($info['host'], 80);
        if (!$fp){  
            echo 'error fsockopen';  
        }  
        else{  
            stream_set_blocking($fp,0);  
            $http = "GET ".$info['path']." HTTP/1.0\r\n";      
            $http .= "Host: ".$info['host']."\r\n";      
            $http .= "Connection: Close\r\n\r\n";  
            $result = fputs($fp,$http);  
            echo $result;
            fclose($fp);  
        } */
        
        //p(curl('http://teambuy.zero.com/api/index/test',['a' => 1,'b' => 2,'c' => 3],'post'));
        echo date('Y-m-d H:i:s');
    }

    /**
     * 物流信息查询 
     */
    public function logistical(){
        try{
            $this->safeChecked();
            /*验证*/
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $id = I('param.order_id');
            $Obj = M('order');
            $info = $Obj->find($id);
            $param = [
                'com' => $info['postage_code'],
                'num' => $info['postage_num']
            ];
            //判断是否存在缓存物流信息
            $result = S($param['com'].$param['num']);
            if($result){
                $this->res_data['data'] = $result;
            }else{
                $result = selectPostage($param);
                //有returnCode字段返回表示查询失败
                if(isset($result['returnCode'])){
                    debug($result);
                }
                //若返回state = 3表示该包裹已签收
                if($result['state'] == 3){
                    //订单若为待收货状态则修改为待评价
                    if($info['status'] == 3){
                        $Obj->startTrans();
                        $flag = $Obj->where(array('id' => $id))->save(array('status' => 4,'tstamp' => time()));
                        if(!$flag){
                            $Obj->rollback();
                            debug($Obj->_sql());
                        }
                        $Obj->commit();
                    }
                }
                //物流信息缓存一天
                if($result['data']){
                    S($param['com'].$param['num'],$result['data'],86400);
                }
                $this->res_data['data'] = $result['data']?:[];
            }
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }
}